<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup as AuthGroups;
use app\admin\validate\AuthGroup as GroupValidate;
use think\Request;

class AuthGroup extends Common
{
    private $cModel;   //当前控制器关联模型

    public function initialize()
    {
        parent::initialize();
        $this->cModel = new AuthGroups;   //别名：避免与控制名冲突
    }

    public function index()
    {
        $dataList = $this->cModel->paginate(10);
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $validate = new GroupValidate;
            if (!$validate->scene('add')->check($data)) {
                return json(['code' => 404, 'msg' => $validate->getError(), 'data' => null]);
            }
            $result = $this->cModel->allowField(true)->save($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '成功', 'data' => null]);
            } else {
                return json(['code' => 0, 'msg' => $this->cModel->getError(), 'data' => null]);
            }
        }
        return $this->fetch();
    }

    public function tree($page = 1, $limit = 10)
    {
        return $this->cModel->pageTable($page, $limit);
    }

    /*
     * 用户用户id获取选中的权限节点list
     */
    public function getUserRule($id)
    {
        $auth_group = $this->cModel->get($id);
        $rule = new \app\admin\model\AuthRule();
        return json($rule->getUserRule($auth_group['rules']));

    }

    public function edit(Request $request, $id)
    {
        if ($request->isPost()) {
            $data = $request->post();
            $validate = new GroupValidate;
            if (!$validate->scene('edit')->check($data)) {
                return json(['code' => 404, 'msg' => $validate->getError(), 'data' => null]);
            }
            $auth_group = AuthGroups::get($id);
            $result = $auth_group->save($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '成功', 'data' => null]);
            } else {
                return json(['code' => 0, 'msg' => $this->cModel->getError(), 'data' => null]);
            }
        } else {
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    /*
     * ajax更新部分数据
     */
    public function ajax(Request $request, $id)
    {
        if ($request->isPost()) {
            if($id==1){
                return json(['code' => 404, 'msg' => '你无法禁用超级管理员', 'data' => null]);
            }
            $data = $request->post();
            $validate = new GroupValidate;
            if (!$validate->scene('ajax')->check($data)) {
                return json(['code' => 404, 'msg' => $validate->getError(), 'data' => null]);
            }
            $auth_group = AuthGroups::get($id);
            $result = $auth_group->save($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '成功', 'data' => null]);
            } else {
                return json(['code' => 404, 'msg' => $this->cModel->getError(), 'data' => null]);
            }
        } else {
            return json(['code' =>404, 'msg' => '请求不被允许', 'data' => null]);
        }
    }

    public function delete($id)
    {
        if (request()->isPost()) {
            //超级管理员不能删除
            if($id==1||strpos($id,'1,'!==false)){
                return json(['code' => 404, 'msg' => '超级管理员不能删除', 'data' => null]);
            }
            $result = $this->cModel->where('id','in',$id)->delete();
            //级联删除角色的用户
//            $where = ['group_id' => ['in', $id_arr]];
//            $agaModel = new AuthGroupAccess();
//            $agaModel->where($where)->delete();
            if ($result) {
                return json(['code' => 0, 'msg' => '成功', 'data' => null]);
            } else {
                return json(['code' => 404, 'msg' => '删除失败', 'data' => null]);
            }
        }
    }

    public function authUser($id)
    {
        $agaModel = new AuthGroupAccess();
        if (request()->isPost()) {
            $data = input('post.');
            $group_id = $data['id'];   //当前角色ID
            $uid = $data['uid'];   //新提交授权用户数组:[1,2,3,4....]

            $oldData = $agaModel->where(['group_id' => $group_id])->select();
            $oldUser = array();   //以前授权用户
            $mixArr = array();   //交集授权用户
            $addArr = array();   //新增授权用户
            $delArr = array();   //删除授权用户
            foreach ($oldData as $k => $v) {
                $oldUser[] = $v['uid'];
            }
            $mixArr = array_intersect($uid, $oldUser);
            if (empty($mixArr)) {
                $addArr = $uid;
                $delArr = $oldUser;
            } else {
                $addArr = array_diff($uid, $mixArr);
                $delArr = array_diff($oldUser, $mixArr);
            }
            if (!empty($delArr)) {
                $where = [
                    'group_id' => $group_id,
                    'uid' => ['in', $delArr],
                ];
                $agaModel->where($where)->delete();
            }
            if (!empty($addArr)) {
                $addList = array();
                foreach ($addArr as $k => $v) {
                    $addList[] = ['group_id' => $group_id, 'uid' => $v];
                }
                $agaModel->saveAll($addList, false);
            }
            return ajaxReturn(lang('action_success'), url('index'));
        } else {
            $authList = $agaModel->alias('a')->join('user u', 'a.uid = u.id')
                ->field('u.id,u.username,u.name')
                ->where(['group_id' => $id])->select();   //已经拥有权限用户

            $uModel = new User();
            $userList = $uModel->field('id,username,name')->select();   //全部用户

            foreach ($userList as $k => $v) {   //删除全部用户中已授权用户
                foreach ($authList as $k2 => $v2) {
                    if ($v['id'] == $v2['id']) {
                        unset($userList[$k]);
                        break;
                    }
                }
            }
            $this->assign('id', $id);
            $this->assign('userList', $userList);
            $this->assign('authList', $authList);
            return $this->fetch();
        }
    }
}